package customer

import (
	"air_chat/common/response"
	"air_chat/internal/dto/req"
	"air_chat/internal/validate"
	"air_chat/util"
	"fmt"
	"github.com/gin-gonic/gin"

	"air_chat/internal/model"
	uuid "github.com/satori/go.uuid"
)

// Register
// @Summary 用户注册
// @Schemes
// @Description 用户注册
// @Tags 用户相关
// @Accept json
// @Produce json
// @Param userinfo body req.AddUserDto true "用户信息"
// @Success 200 {string} json "{"code":200,"msg":"","data":""}"
// @Router /customer/register [post]
func Register(c *gin.Context) {
	var json req.AddUserDto
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Fail(c, validate.Translate(err))
		return
	}

	if json.Password != json.PasswordConfirm {
		response.Fail(c, "两次密码不一致")
		return
	}

	uuidv4 := uuid.NewV4()
	userBase := model.UserAccount{
		Identity: uuidv4.String(),
		Password: util.Md5String(json.Password),
		Nickname: json.Nickname,
		Mobile:   json.Mobile,
	}

	err := model.CreateUser(&userBase)
	if err != nil {
		msg := fmt.Sprintf("create user faield error:%s", err.Error())
		response.Fail(c, msg)
		return
	}
	response.Success(c, gin.H{})
}

// 对该方法生成 swagger 文档
// @Summary 用户登录
// @Schemes
// @Description 用户登录
// @Tags 用户相关
// @Accept json
// @Produce json
// @Param userinfo body req.LoginByMobileDto true "用户信息"
// @Success 200 {string} json "{"code":200,"msg":"","data":""}"
// @Router /customer/login [post]
func Login(c *gin.Context) {
	var json req.LoginByMobileDto
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Fail(c, validate.Translate(err))
		return
	}
	user, err := model.GetUserByMobile(json.Mobile)
	if err != nil {
		msg := fmt.Sprintf("通过手机号查询用户失败: %s", err.Error())
		response.Fail(c, msg)
		return
	}

	if user.Password != util.Md5String(json.Password) {
		response.Fail(c, "密码错误")
		return
	}
	token, err := util.ReleaseToken(user.Identity, user.Nickname)
	if err != nil {
		msg := fmt.Sprintf("签发token失败: %s", err.Error())
		response.Fail(c, msg)
		return
	}
	response.Success(c, gin.H{
		"token": token,
	})
}
